﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using UCL;
using UCL.Forms;
using UCL.Data;

namespace DBKit5
{
    /// <summary>
    /// 2013-6-7 by sutroon
    /// </summary>
    public partial class frmConnectionList : Form
    {
        AppDataHelper adh = new AppDataHelper();
        public frmConnectionList()
        {
            InitializeComponent();
        }

        private void frmConnectionList_Load(object sender, EventArgs e)
        {
            MenuItemClickConfig();
            this.FormLoad_Connections();
            this.FormLoad_Group();
        }

        /// <summary>
        /// 读取连接列表
        /// </summary>
        /// <param name="search"></param>
        private void FormLoad_Connections(string search = "")
        {
            if (search.Length == 0 && tvGroup.SelectedNode != null) search = "GroupID=" + tvGroup.SelectedNode.Name;
            if (search.Length > 0) search = " where " + search;
            dgvList.DataSource = adh.ExecuteDataTable("select * from tconnections" + search);
        }

        /// <summary>
        /// 读取分组列表
        /// </summary>
        private void FormLoad_Group()
        {
            tvGroup.Nodes.Clear();
            string xml = adh.GetCatalogTreeText("CONNECTION_GROUP");
            tvGroup.LoadXmlString(xml);
            tvGroup.ExpandAll();
        }

        private void MenuItemClickConfig()
        {
            #region cmiTable

            cmi编辑ToolStripMenuItem.Click += new EventHandler(cmiMenuItem_Click);
            cmi复制ToolStripMenuItem.Click += new EventHandler(cmiMenuItem_Click);
            cmi删除ToolStripMenuItem.Click += new EventHandler(cmiMenuItem_Click);
            cmi设为默认ToolStripMenuItem.Click += new EventHandler(cmiMenuItem_Click);
            cmi刷新ToolStripMenuItem.Click += new EventHandler(cmiMenuItem_Click);
            cmi新增ToolStripMenuItem.Click += new EventHandler(cmiMenuItem_Click);
            cmi导出ToolStripMenuItem.Click += new EventHandler(cmiMenuItem_Click);
            cmi导入ToolStripMenuItem.Click += new EventHandler(cmiMenuItem_Click);
            cmi显示全部ToolStripMenuItem.Click += new EventHandler(cmiMenuItem_Click);
            #endregion

            #region cmiGroup

            cmig编辑分组ToolStripMenuItem.Click += new EventHandler(cmigMenuItem_Click);
            cmig删除分组ToolStripMenuItem.Click += new EventHandler(cmigMenuItem_Click);
            cmig新增分组ToolStripMenuItem.Click += new EventHandler(cmigMenuItem_Click);
            #endregion
        }

        // 连接列表右键菜单事件
        private void cmiMenuItem_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem mi = (ToolStripMenuItem)sender;
            switch (mi.Name)
            {
                case "cmi编辑ToolStripMenuItem":
                    if (dgvList.CurrentCell == null) return;
                    this.OpenDialog<UControls.frmConnectionEdit>(() => new UControls.frmConnectionEdit() { RecordID = dgvList.GetCurrentValue("ID").ToString().ToInt(), RefreshHandler = RefreshList });
                    break;
                case "cmi复制ToolStripMenuItem":
                    if (dgvList.CurrentCell == null || dgvList.CurrentCell.Value == DBNull.Value) return;
                    Clipboard.SetText(dgvList.CurrentCell.Value.ToString());
                    break;
                case "cmi删除ToolStripMenuItem":
                    if (dgvList.CurrentCell == null) return;
                    adh.Delete("tconnections", "ID=" + dgvList.GetCurrentValue("ID").ToString().ToInt());
                    FormLoad_Connections();
                    break;
                case "cmi设为默认ToolStripMenuItem":
                    if (dgvList.CurrentCell == null) return;
                    adh.ExecuteNonQuery("update tconnections set IsDefault=0");
                    adh.Update("tconnections", "IsDefault=1", "ID=" + dgvList.GetCurrentValue("ID").ToString().ToInt());
                    FormLoad_Connections();
                    break;
                case "cmi刷新ToolStripMenuItem":
                    FormLoad_Connections();
                    break;
                case "cmi新增ToolStripMenuItem":
                    this.OpenDialog<UControls.frmConnectionEdit>(() => new UControls.frmConnectionEdit() { RefreshHandler = RefreshList });
                    break;
                case "cmi导出ToolStripMenuItem":
                    this.ShowSaveFileDialog("Excel file (*.xls)|*.xls", (fn) => { return ((DataTable)dgvList.DataSource).SaveToExcel(fn); });

                    break;
                case "cmi导入ToolStripMenuItem":
                    this.ShowOpenFileDialog("Excel file (*.xls)|*.xls", (fn) =>
                    {
                        ExcelHelper eh = new ExcelHelper(fn);
                        DataTable dt = eh.ExecuteDataTable("select * from [Sheet1$]");
                        StringBuilder sb = new StringBuilder();
                        foreach (DataRow r in dt.Rows)
                        {
                            sb.AppendFormat("insert into tconnections (GroupID, Name, HostName, Port, LoginID, Password, Database, ProductName, Ordinal, IsDefault, CreatedTime) values ('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}', '{10}');", r["GroupID"], r["Name"], r["HostName"], r["Port"], r["LoginID"], r["Password"], r["Database"], r["ProductName"], r["Ordinal"], r["IsDefault"], r["CreatedTime"].ToString().ToDateTime().ToString("s"));
                        }
                        adh.ExecuteNonQuery(sb.ToString());
                        MessageBox.Show(adh.MessageSet.Count == 0 ? "导入成功!" : adh.MessageSet.ToString(Environment.NewLine));
                        FormLoad_Connections();
                    });
                    break;
                case "cmi显示全部ToolStripMenuItem":
                    this.FormLoad_Connections();
                    break;
            }
        }

        private void RefreshList()
        {
            this.FormLoad_Connections();
        }

        // 分组列表右键菜单事件
        private void cmigMenuItem_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem mi = (ToolStripMenuItem)sender;
            int id = tvGroup.SelectedNode.Name.ToInt();
            switch (mi.Name)
            {
                case "cmig编辑分组ToolStripMenuItem":
                    if (tvGroup.SelectedNode == null) return;
                    this.OpenDialog<frmCatalogEdit>(() => new frmCatalogEdit() { PrimaryID = id, RefreshHandler = FormLoad_Group });
                    break;
                case "cmig删除分组ToolStripMenuItem":
                    if (tvGroup.SelectedNode == null) return;
                    if (adh.SelectString("tgeneralcatalog", "ParentID=" + id, "count(ID)").ToInt() > 0)
                    {
                        MessageBox.Show("无法删除,请先删除子分组!");
                        return;
                    }
                    if (adh.SelectString("tconnections", "GroupID=" + id, "count(ID)").ToInt() > 0)
                    {
                        MessageBox.Show("该分组下有连接数据,无法删除");
                        return;
                    }
                    adh.Delete("tgeneralcatalog", "ID=" + id);
                    FormLoad_Group();
                    break;
                case "cmig新增分组ToolStripMenuItem":
                    if (tvGroup.SelectedNode == null) return;
                    this.OpenDialog<frmCatalogEdit>(() => new frmCatalogEdit() { ParentID = id, ExTags = "CONNECTION_GROUP", RefreshHandler = FormLoad_Group });
                    break;
            }
        }

        private void tvGroup_AfterSelect(object sender, TreeViewEventArgs e)
        {
            string search = tvGroup.SelectedNode.Level == 0 ? "1=1" : "GroupID=" + tvGroup.SelectedNode.Name;
            this.FormLoad_Connections(search);
        }
    }
}
